<template>
	<div class="app-container">
		<div class="table-wrapper">
			<h4>建筑物易损性信息</h4>
			<el-form :inline="true" ref="formRef" :rules="rules" label-position="right" :model="params" label-width="200px">
				<div class="form-inline">
					<el-row justify="center">
						<el-col :span="11">
							<el-form-item label="编号：" class="form-item" prop="number"><el-input v-model="params.number"
									placeholder="" clearable disabled /></el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item label="用途：">
								<el-col :span="12">
									<el-form-item prop="use0">
										<el-select v-model="params.use0" placeholder="请选择" class="form-select"
											@change="useChange" clearable>
											<el-option v-for="item in useOptions" :key="item.value" :label="item.label"
												:value="item.value"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
								<el-col :span="11">
									<el-form-item prop="use1">
										<el-select v-model="params.use1" placeholder="请选择" class="form-select" clearable>
											<el-option v-for="item in use1Options" :key="item.value" :label="item.label"
												:value="item.value"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center">
						<el-col :span="11">
							<el-form-item label="区域：" class="form-item" prop="region">
								<el-form-item prop="province" style="width:120px;margin-right:10px;">
									<el-select v-model="params.province" placeholder="请选择省" @change="chooseProvince"
										clearable disabled value-key="id">
										<el-option v-for="item in provinceData" :key="item.id" :label="item.name"
											:value="item"></el-option>
									</el-select>
								</el-form-item>
								<el-form-item prop="city" style="width:120px;margin-right:10px;">
									<el-select v-model="params.city" placeholder="请选择市" @change="chooseCity" clearable
										disabled value-key="id">
										<el-option v-for="item in cityData" :key="item.id" :label="item.name"
											:value="item"></el-option>
									</el-select>
								</el-form-item>
								<el-form-item prop="county" style="width:120px;">
									<el-select v-model="params.county" placeholder="请选择县" @change="chooseCounty" clearable
										disabled value-key="id">
										<el-option v-for="item in areaData" :key="item.id" :label="item.name"
											:value="item"></el-option>
									</el-select>
								</el-form-item>
							</el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item label="结构类型：" class="form-item" prop="structureType">
								<el-col :span="12">
									<el-form-item prop="structureType">
										<el-select v-model="params.structureType" placeholder="请选择" class="form-select"
											@change="structureTypeChange" clearable disabled>
											<el-option v-for="item in structureTypeOptions" :key="item.value"
												:label="item.label" :value="item.value"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
								<el-col :span="11">
									<el-form-item prop="structureType1">
										<el-select v-model="params.structureType1" placeholder="请选择" class="form-select"
											clearable disabled>
											<el-option v-for="item in structureType1Options" :key="item.value"
												:label="item.label" :value="item.value"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center">
						<el-col :span="11">
							<el-form-item label="层数：" class="form-item" prop="cs">
								<el-select v-model="params.cs" placeholder="请选择" class="form-select" clearable>
									<el-option v-for="item in csOptions" :key="item.value" :label="item.label"
										:value="item.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item label="建造年代：" class="form-item" prop="years">
								<el-select v-model="params.years" placeholder="请选择" class="form-select" clearable>
									<el-option v-for="item in yearsOptions" :key="item.value" :label="item.label"
										:value="item.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center">
						<el-col :span="11">
							<el-form-item label="设防情况：" class="form-item" prop="fortification">
								<el-select v-model="params.fortification" placeholder="请选择" class="form-select" clearable
									disabled>
									<el-option v-for="item in fortificationOptions" :key="item.value" :label="item.label"
										:value="item.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item prop="createTime" label="维护时间:">
								<el-date-picker clearable disabled v-model="params.createTime" type="date"
									placeholder="开始时间" value-format="YYYY-MM-DD" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center">
						<el-col :span="11">
							<el-form-item label="维护人：" class="form-item" prop="userName"><el-input v-model="params.userName"
									placeholder="" clearable disabled /></el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item label="维护人所属单位：" class="form-item" prop="maintainerUnit">
								<el-input v-model="params.maintainerUnit" placeholder="" clearable disabled />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center">
						<el-col :span="22">
							<el-form-item label="备注：" class="form-item" prop="info" style="width: 100%;">
								<el-input type="textarea" v-model="params.info" placeholder="" clearable />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="end">
						<el-form-item class="bottom-button">
							<el-button type="primary" @click="onSave(formRef)" v-if="!isAdmin"><el-icon><Select /></el-icon>保存</el-button>
							<el-button @click="onRest(formRef)"><el-icon>
									<Refresh />
								</el-icon>重置</el-button>
						</el-form-item>
					</el-row>
				</div>
			</el-form>

			<div v-if="tableData.length">
				<h4>地震易损性矩阵</h4>
				<el-table class="listTables" ref="multipleTableRef" border :data="tableData" style="width: 100%"
					:cell-style="{ border: '1px solid #e5ebf7' }"
					:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
					<el-table-column prop="damage" label="破坏程度" align="right" width="150">
						<el-table-column prop="intensity" label="烈度" width="150"></el-table-column>
					</el-table-column>
					<el-table-column header-align="center" align="center" label="基本完好">
						<template #default="{ row }">
							<el-input type="number" v-model="row.basicallyIntact" placeholder="请输入" maxlength="10" />
							<!-- <span>{{ row.basicallyIntact }}</span> -->
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center" label="轻微破坏">
						<template #default="{ row }">
							<el-input type="number" v-model="row.minorDamage" placeholder="请输入" maxlength="10" />
							<!-- <span>{{ row.minorDamage }}</span> -->
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center" label="中等破坏">
						<template #default="{ row }">
							<el-input type="number" v-model="row.moderateDamage" placeholder="请输入" maxlength="10" />
							<!-- <span>{{ row.moderateDamage }}</span> -->
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center" label="严重破坏">
						<template #default="{ row }">
							<el-input type="number" v-model="row.seriousDamage" placeholder="请输入" maxlength="10" />
							<!-- <span>{{ scope.row.seriousDamage }}</span> -->
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center" label="倒塌">
						<template #default="{ row }">
							<el-input type="number" v-model="row.collapse" placeholder="请输入" maxlength="10" />
							<!-- <span>{{ scope.row.collapse }}</span> -->
						</template>
					</el-table-column>
				</el-table>
			</div>

			<div v-if="showLineChart">
				<h4>地震易损性曲线</h4>
				<!-- echarts图表 -->
				<div ref="lineChartRef" class="seismic-fragility-line"></div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { computed, reactive, toRefs } from 'vue';
// 获取用户信息
import { getInfo } from '@/api/login';
// 引入接口
import {
	queryBvInformationApi, //查询信息
	updateBuildingAreaInfoApi, //修改建筑物区域特征信息
} from "@/api/importData/buildingAreaInfo.js";
import { getProvince, getChildArea } from '@/api/system/division';
// 引入echarts
import * as echarts from 'echarts';
// 状态管理模块
import useUserStore from '@/store/modules/user';
import useDictStore from '@/store/modules/dict';
// 获取pinia
const userStore = useUserStore();
const dictStore = useDictStore();
// 用户名
const userName = computed(() => userStore.name || '');
// 所属机构名称
const orgName = computed(() => userStore.orgName || '');
// 是否管理员
const isAdmin = computed(() => userStore.isAdmin || false);
// 获取当前实例
const { proxy } = getCurrentInstance();
// 当前路由对象
const route = useRoute();

// 表单对象
const formRef = ref();
// 图表显示隐藏控制
let showLineChart = ref(true);

const data = reactive({
	// 表单参数
	params: {
		number: '', //编号
		use0: '', //用途
		use1: '', //用途
		region: '', //区域
		province: '', //省
		city: '', //市
		county: '', //区县
		structureType: '', //结构类型
		structureType1: '',
		cs: '', //层数
		years: '', //建造年代
		fortification: '', //设防情况
		userName: '', //维护人
		createTime: '', //维护时间
		maintainerUnit: '', //维护人所属单位
		info: '', //备注
	},
	// 表单验证规则
	rules: {
		// number: [{ required: true, message: '请选择', trigger: 'blur' }],
		fortification: [{ required: true, message: '请选择', trigger: 'change' }],
		years: [{ required: true, message: '请选择', trigger: 'change' }],
		province: [{ required: true, message: '请选择', trigger: 'change' }],
		structureType: [{ required: true, message: '请选择', trigger: 'change' }]
	},
	// 用途
	useOptions: dictStore.useOptions || [],
	use1Options: [],
	// 结构类型
	structureTypeOptions: dictStore.structureTypeOptions || [],
	structureType1Options: [],
	// 层数
	csOptions: dictStore.csOptions || [],
	// 建造年代
	yearsOptions: dictStore.yearsOptions || [],
	// 设防情况
	fortificationOptions: dictStore.fortificationOptions || [],
	//表格
	tableData: [
		{
			bs: '',
			sl: '',
			ml: '',
			el: '',
			c: ''
		}
	]
});
const {
	// 表单数据
	params,
	// 表单验证规则
	rules,
	// 用途选项
	useOptions,
	use1Options,
	// 结构类型选项
	structureTypeOptions,
	structureType1Options,
	// 层数选项
	csOptions,
	// 建造年代选项
	yearsOptions,
	// 设防情况选项
	fortificationOptions,
	// 表格数据
	tableData,
} = toRefs(data);

// 表单初始值
let initFormParms = { ...params.value };

// 行政区划选择
const provinceData = ref([]); //省
const cityData = ref([]); //市
const areaData = ref([]); //区、县
// 获取省份数据
function getProvinceData() {
	getProvince().then(response => {
		provinceData.value = response.data;
	});
}
// 选择省份
function chooseProvince(value) {
	params.value.city = null;
	params.value.county = null;
	params.value.province = value.name;
	cityData.value = [];
	areaData.value = [];
	getChildArea(value.id).then(response => {
		cityData.value = response.data;
	});
}
// 选择城市
function chooseCity(value) {
	params.value.city = value.name;
	params.value.county = null;
	areaData.value = [];
	getChildArea(value.id).then(response => {
		areaData.value = response.data;
	});
}
// 选择区县
function chooseCounty(value) {
	params.value.county = value.name;
}

// 结构类型选择
const structureTypeChange = val => {
	const structureTypes = structureTypeOptions.value.find(item => item.value === val);
	if (structureTypes) {
		params.value.structureType1 = '';
		structureType1Options.value = structureTypes.children;
	}
};
// 选择用途
const useChange = val => {
	const use = useOptions.value.find(item => item.value === val);
	if (use) {
		params.value.use1 = '';
		use1Options.value = use.children;
	}
};

//地震易损性矩阵表格查询
const onSearch = () => {
	queryBvInformationApi({
		number: route.query.number,
		dataType: route.query.dataType,
		id: route.query.id,
		province:route.query.province.split('-')[0],
	}).then(res => {
		const { code, data } = res;
		if (code == 200 && data) {
			const { entity, matrix, curve } = data;
			// 基础信息
			if (entity) {
				params.value = { ...entity };
				// 获取维护人信息
				if (params.value.createUser) {
					getUserInfo(params.value.createUser)
				}
			}
			// 矩阵
			tableData.value = [];
			if (matrix && matrix.length) {
				matrix.map(item => {
					tableData.value.push({ ...item });
				})
			}
			// 图表
			if (curve && curve.length) {
				// 渲染折线图
				renderChart(curve);
			} else {
				// 隐藏折线图区域
				showLineChart.value = false;
			}
		} else {
			proxy.$modal.msgWarning('建筑物易损性信息获取失败！');
		}
	}).catch(err => {
		console.log(err.message);
	});
};
// 获取用户
function getUserInfo(userId) {
	getInfo(userId).then(response => {
		const { code, user } = response;
		if (user) {
			params.value.userName = user.userName;
			params.value.maintainerUnit = user.orgName;
		}
	});
};

//保存
const onSave = async formEl => {
	if (!formEl) return;
	// 表单验证
	await formEl.validate((valid, fields) => {
		if (valid) {
			updateBuildingAreaInfoApi({
				//基础信息
				...params.value,
				// 矩阵数据
				matrixParam: tableData.value || [],
			}).then(res => {
				const { code, data, message } = res;
				if (code == 200) {
					proxy.$modal.msgSuccess('保存成功！');
				} else {
					proxy.$modal.msgWarning(message || '保存失败！');
				}
			}).catch(err => {
				console.log(err.message || '保存失败！');
			})
		} else {
			proxy.$modal.msgWarning('表单验证失败，请检测填写数据！');
		}
	});
};
//重置
const onRest = formEl => {
	// 重置表单，方式一
	formEl.resetFields(initFormParms);
	// 重置表单，方式二
	// proxy.resetForm('formRef');
};

//折线图
let myChart = null;
function renderChart(data) {
	if (!myChart) {
		myChart = echarts.init(proxy.$refs['lineChartRef']);
	}
	if (data && data.length) {
		// x轴
		let xAxisData = [];
		// 预测值
		let cData = [];
		let edData = [];
		let mdData = [];
		let sdData = [];
		// 修正值
		let correctionData = [];
		// 遍历赋值
		data.map((item, index) => {
			if (item.breakState == "SD") {
				item.fim && sdData.push(item.fim);
				xAxisData.push(item.im);
			}
			if (item.breakState == "MD") {
				item.fim && mdData.push(item.fim);
			}
			if (item.breakState == "ED") {
				item.fim && edData.push(item.fim);
			}
			if (item.breakState == "CD") {
				item.fim && cData.push(item.fim);
			}
			if (item.breakState == "C") {
				item.fim && correctionData.push(item.fim);
			}
		});
		// 排序
		xAxisData.sort((a, b) => a < b ? -1 : 1);
		const option = {
			toolbox: {
				//echart保存为图片
				show: true,
				feature: {
					mark: {
						show: true
					},
					restore: {
						show: true
					},
					saveAsImage: {
						show: true,
						pixelRatio: 1,
						title: '保存为图片',
						type: 'png',
						lang: ['点击保存']
					}
				}
			},
			legend: {
				data: ['轻微(SD)', '中等(MD)', '严重(ED)', '毁坏(Collapse)', '修正(correction)']
			},
			tooltip: {
				trigger: 'axis'
			},
			xAxis: {
				name: 'PGA:(IM)',
				type: 'category',
				data: xAxisData
			},
			yAxis: {
				name: '超越概率',
				type: 'value',
				axisLabel: {
					formatter: '{value}%'
				}
			},
			// 数据颜色 '#739cef', '#ff0000'
			color: ['#de182b', '#2ad12e', '#030303', '#0401ed', '#ff0000'],
			series: [
				// 预测值
				{
					name: '轻微(SD)',
					data: sdData,
					smooth: true,
					type: 'line'
				},
				{
					name: '中等(MD)',
					data: mdData,
					smooth: true,
					type: 'line'
				},
				{
					name: '严重(ED)',
					data: edData,
					smooth: true,
					type: 'line'
				},
				{
					name: '毁坏(Collapse)',
					data: cData,
					smooth: true,
					type: 'line'
				},
				// 修正值
				// {
				// 	name: '修正(correction)',
				// 	data: correctionData,
				// 	smooth: true,
				// 	type: 'line'
				// }
			]
		};
		myChart.clear();
		myChart.setOption(option, true);
	}
};
// 挂载后
onMounted(() => {
	// 获取行政区划数据
	// 初始化获取数据
	getProvinceData();
	onSearch();
});
// 卸载前
onBeforeUnmount(() => {
	if (myChart) {
		myChart.dispose();
		myChart = null;
	}
});
</script>

<style lang="scss" scoped>
.table-wrapper {
	position: relative;

	h4 {
		font-size: 16px;
		font-weight: bold;
		color: #107ce5;
		text-align: center;
	}
}

.form-inline {
	.el-form-item {
		margin-right: 0;
	}
}

:deep(.el-table.listTables) {
	thead.is-group th {
		background: none;
	}

	thead.is-group tr:first-of-type th:first-of-type {
		border-bottom: none;
	}

	thead.is-group tr:first-of-type th:first-of-type:before {
		content: '';
		position: absolute;
		width: 1px;
		height: 85px;
		/*这里需要自己调整，根据td的宽度和高度*/
		top: 0;
		left: 0;
		background-color: grey;
		opacity: 0.3;
		display: block;
		transform: rotate(302deg);
		/*这里需要自己调整，根据线的位置*/
		transform-origin: top;
	}

	thead.is-group tr:last-of-type th:first-of-type:before {
		content: '';
		position: absolute;
		width: 1px;
		height: 88px;
		/*这里需要自己调整，根据td的宽度和高度*/
		bottom: 0;
		right: 0;
		background-color: grey;
		opacity: 0.3;
		display: block;
		transform: rotate(302deg);
		/*这里需要自己调整，根据线的位置*/
		transform-origin: bottom;
		/* background:red; */
	}
}

// 图表样式
.seismic-fragility-bar,
.seismic-fragility-line {
	width: 100%;
	height: 400px;
	margin: 20px auto;
}
</style>
